#!/bin/bash

# Pinning the packages of specific PPA
#
# unattended-upgrade:
# unattended-upgrade will temporarily set APT pinning for the archives
# it will ignore the pinning configuration for PPAs that are not listed
# in the Allowed-Origins list
# we have to add the PPA into this list to prevent unattended from
# setting its pinning priority to -32768
# we also need to tell unattended-upgrade to allow the downgrade
# in case the packages in the PPA have older versions than the ones
# from Ubuntu archive
add_kobuk_ppa() {
  ppa_id=$1
  team=kobuk-team
  # try to detect if the PPA is specified as fullname
  # example : ppa:canonical-kernel-team/bootstrap
  if [[ ${ppa_id} =~ ppa:([^/]+)/([^/]+)$ ]]; then
    team=${BASH_REMATCH[1]}
    ppa_id=${BASH_REMATCH[2]}
  fi
  distro_id=LP-PPA-${team}-${ppa_id}

  add-apt-repository -y ppa:${team}/${ppa_id}

  cat <<EOF | tee /etc/apt/preferences.d/kobuk-tdx-${team}-${ppa_id}-pin-4000
Package: *
Pin: release o=${distro_id}
Pin-Priority: 4000
EOF

  cat <<EOF | tee /etc/apt/apt.conf.d/99unattended-upgrades-kobuk-${ppa_id}
Unattended-Upgrade::Allowed-Origins {
  "${distro_id}:${UBUNTU_CODENAME}";
};
Unattended-Upgrade::Allow-downgrade "true";
EOF
}

# Add all kobuk given PPAs
add_kobuk_ppas() {
  for ppa in "$@"; do
    add_kobuk_ppa "$ppa"
  done
}

echo "Here is add kubuk ppa"


add_kobuk_ppas ${TDX_PPA:-tdx-release}
